package com.ruoyi.kong.controller;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.kong.domain.KongxSystemProfile;
import com.ruoyi.kong.service.IKongServiceInfoService;
import com.ruoyi.kong.service.IKongxSystemProfileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/kong")
public class KongController extends BaseController {

    /**
     * kong 服务层
     */
    @Autowired
    private IKongxSystemProfileService kongxSystemProfileService;

    @Autowired
    private IKongServiceInfoService kongProxyService;

    /**
     * 激活kong远程连接,kong profile 信息存入 redis 缓存
     *
     * @return
     */
    @PostMapping("/active")
    public AjaxResult active(@RequestBody KongxSystemProfile kongxSystemProfile) {

        if (ObjectUtils.isEmpty(kongxSystemProfile)) {
            return error("kong 配置参数为空，请传递 相关kong 配置参数 做激活操作");
        }

        if (StringUtils.isEmpty(kongxSystemProfile.getUrl())) {
            return error("kong 连接地址为空，无法激活");
        }
        // 根据 kong profile 获取 配置信息 ，存储到redis 缓存中

        int active = kongxSystemProfileService.activeKongServerByProfile(kongxSystemProfile);
        if (active > 0) {
            return success("激活成功");
        }
        return error("无法激活");
    }

    @PostMapping("/stop")
    public AjaxResult stop(@RequestBody KongxSystemProfile kongxSystemProfile) {
        if (ObjectUtils.isEmpty(kongxSystemProfile)) {
            return error("kong 配置参数为空，请传递 相关kong 配置参数 做激活操作");
        }
        return AjaxResult.success(kongxSystemProfileService.stopKongServerByProfile(kongxSystemProfile));
    }


    /**
     * 从缓存中获取 kong 的配置信息
     *
     * @return
     */
    @GetMapping("/profile/info")
    public AjaxResult getKongProfile() {
        KongxSystemProfile kongxSysProfile = kongxSystemProfileService.getKongxSysProfileFormCache();
        return AjaxResult.success("查询成功", kongxSysProfile);
    }


    /**
     * 请求kong 网关 返回kong 信息
     * @return
     */
    @GetMapping("/infos")
    public AjaxResult getKongInfo(){

        Map kongInfos = kongProxyService.getKongInfos();
        return AjaxResult.success("成功",kongInfos);
    }

    /**
     * 请求kong网关 返回kong 状态
     * @return
     */
    @GetMapping("/status")
    public AjaxResult getKongStatus(){
        Map kongStatus = kongProxyService.getKongStatus();
        return AjaxResult.success("成功",kongStatus);
    }
}
